package com.myactiviti;

import jdk.nashorn.internal.ir.CallNode;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.NativeProcessDefinitionQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.junit.Test;
import sun.misc.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * act_ru_task:存储代办任务
 *
 * ProcessInstance:流程定义，发布，启动整体流程控制。
 *
 */
public class test {
    @Test
    public void testRun(){
        ProcessEngine processEngine =   ProcessEngines.getDefaultProcessEngine();
        System.out.println(processEngine);
    }

    @Test
    public void loadActiviticif(){
        //加载指定配置文件
        ProcessEngineConfiguration processEngineConfigurationFromResource = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("config/activiti.cfg.xml");
        ProcessEngine processEngine = processEngineConfigurationFromResource.buildProcessEngine();
        System.out.println("--->"+processEngine.getName());

    }

    @Test
    public void Flowbushu(){
        //流程图部署
        //1、获取processEngine
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //获取RepositoryService部署操作
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        //添加流程,并部署
        Deployment deploy = repositoryService.createDeployment().addClasspathResource("flow/demo1.bpmn")
                .name("请假流程")
                .deploy();
        System.out.println("流程信息"+deploy.getId()+"---->"+deploy);
    }

    //加载zip流程包
    @Test
    public void zipload(){
        InputStream resourceAsStream = this.getClass().getResourceAsStream("flow/demo1.zip");
        //1、获取processEngine
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //获取RepositoryService部署操作
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        Deployment deploy = repositoryService.createDeployment()
                .addZipInputStream(new ZipInputStream(resourceAsStream))
                .deploy();
        System.out.println("流程信息"+deploy.getId()+"---->"+deploy);
    }

    //启动一个流程实例,启动流程
    @Test
    public void test05(){
        //1、获取processEngine
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //
        RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
        //
        ProcessInstance demo1 = runtimeService.startProcessInstanceByKey("demo1");

        System.out.println(demo1.getId());
        System.out.println(demo1.getProcessDefinitionId());


    }

    //查询当前人员的代办任务
    @Test
    public void test6(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();
        List<Task> list = taskService.createTaskQuery()
                .processDefinitionKey("demo1")
                .taskAssignee("lisi")
                .list();
        for (Task t:list){
            System.out.println("实例id"+t.getProcessDefinitionId());
            System.out.println("任务id"+t.getId());
            System.out.println("任务负责人"+t.getAssignee());
            System.out.println("任务名称"+t.getName());
        }
    }

    //流程任务处理（审批完成）审批
    @Test
    public void test7(){
        //zhangsan处理完后，流转到lisi
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();
        Task task = taskService.createTaskQuery().processDefinitionKey("demo1").taskAssignee("zhangsan").singleResult();
        //完成任务
        taskService.complete(task.getId());
    }

    //查询流程定义,查询已经存在流程信息
    @Test
    public void test08(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> demo1 = processDefinitionQuery.processDefinitionKey("demo1").orderByDeploymentId().desc().list();
        for (ProcessDefinition processDefinition : demo1) {
            System.out.println("------>"+processDefinition.getId());
            System.out.println("------>"+processDefinition.getName());
            System.out.println("------>"+processDefinition.getKey());
            System.out.println("------>"+processDefinition.getDeploymentId());
        }
    }
    /**
     * 删除流程
     */
    @Test
    public  void test9(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        //第二参数，是判定删除时，是否识别当前流程是否正在运行,当为true时，即使有流程启动也可删除。
        //为false，只能删除没有启动流程 act_re_deployment中id
        repositoryService.deleteDeployment("80001",false);

    }

    /**
     * 下载工作流文件
     */
    @Test
    public void test10(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("demo1")
                .singleResult();
        //获取图片文件流
       // InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
        //获取bpm文件流
        InputStream resourceAsStream1 = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName());
        File fjpg = new File("D:/fpjg.png");
        File fbpm = new File("D:/fbpmn.bpmn");
        OutputStream fileOutputStream = null;
        OutputStream fileOutputStream1 = null;
        try{
             fileOutputStream = new FileOutputStream(fjpg);
             fileOutputStream1 = new FileOutputStream(fbpm);
            byte[] b = new byte[1024*8];
            int len = 0;
            while((len=resourceAsStream1.read(b))!=-1){
                fileOutputStream1.write(b, 0, len);
                        }
        }catch (Exception e){

        }finally {
            try {
                fileOutputStream.close();
                fileOutputStream1.close();
                resourceAsStream1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }



    }

    /**
     * 查询历史信息
     */
    @Test
    public void test11(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = defaultProcessEngine.getHistoryService();
        HistoricActivityInstanceQuery historicActivityInstanceQuery = historyService.createHistoricActivityInstanceQuery();
        List<HistoricActivityInstance> demo11 = historicActivityInstanceQuery.processDefinitionId("demo1:1:40003").orderByHistoricActivityInstanceEndTime().desc().list();
        for (HistoricActivityInstance historicActivityInstance : demo11) {
            System.out.println("------>"+historicActivityInstance.getActivityName());
            System.out.println("------>"+historicActivityInstance.getActivityId());
            System.out.println("------>"+historicActivityInstance.getTaskId());
            System.out.println("------>"+historicActivityInstance.getAssignee());
            System.out.println("------>"+historicActivityInstance.getProcessDefinitionId());
            System.out.println("------>"+historicActivityInstance.getActivityType());
            System.out.println("---------------------------------------------------->");
        }
    }


    /**
     * 通过businessKey关联业务数据
     * eg:
     * 业务数据：
     * id       name        yuanyin
     * 1001      wjy         年假
     *创建完成后数据库中business_key,即为关联字段
     */
    @Test
    public void test12(){
        //1、创建ProcessEngines对象
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2、创建服务组件
        RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
        //启动activiti流程
        ProcessInstance demo1 = runtimeService.startProcessInstanceByKey("demo1", "1001");
        //打印关联数据
        System.out.println("BusinessKey:"+demo1.getBusinessKey());


    }


    /**
     * 流程挂起，与释放。流程挂起后，所有该流程涉及的代办流程将全部挂起。表中状态字段：SUSPENSION_STATE_
     * 挂起状态任务：执行流程会报：Cannot complete a suspended task
     */
    @Test
    public void  test13(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("demo1")
                .singleResult();
        //获取流程挂起状态
        boolean suspended = processDefinition.isSuspended();
        if (suspended) {
            repositoryService.activateProcessDefinitionById(
                    processDefinition.getId(),//流程id
                    true,//激活
                    null);//日期
            System.out.println("---------》流程激活");
        }else{
            repositoryService.suspendProcessDefinitionById(
                    processDefinition.getId(),//流程id
                    true,//激活
                    null);//日期
            System.out.println("---------》流程挂起");
        }
    }

    /**
     * 单个正在进行的流程挂起
     */
    @Test
    public void test14(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId("50001")//act_ru_task表中proc_inst_id
                .singleResult();
        boolean suspended = processInstance.isSuspended();
        if (suspended) {
            runtimeService.activateProcessInstanceById(processInstance.getId());
            System.out.println("---------》流程激活");
        }else{
            runtimeService.suspendProcessInstanceById(processInstance.getId());
            System.out.println("---------》流程挂起");
        }

    }

}
